package com.yuncool.jx3robot.mirai.handle;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuncool.jx3robot.common.constant.MiraiConst;
import com.yuncool.jx3robot.common.util.AllMatchKeyMethod;
import com.yuncool.jx3robot.common.util.NoAllMatchKeyMethod;
import com.yuncool.jx3robot.mirai.config.MiraiConfig;
import com.yuncool.jx3robot.mirai.entily.*;
import com.yuncool.jx3robot.mirai.mapper.QqGroupMapper;
import com.yuncool.jx3robot.service.JxQueryApiService;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * qq消息处理类
 */
@Component
@Slf4j
public class MessageHandle {
    //关键字功能
    private static final Map<String, AllMatchKeyMethod> allKey = new HashMap<>();
    private static final Map<String, NoAllMatchKeyMethod> noAllKey = new HashMap<>();
    private static final Map<String, String> mindMap = new HashMap<>();
    private static final Set<String> mindSet;
    private static List<String> imageUrls = new ArrayList<>();
    private static Set<QqGroup> groupSet = new HashSet<>();

    static {
        //初始化心法
        mindMap.put("bx", "冰心诀");
        mindMap.put("nx", "云裳心经");
        mindMap.put("hj", "花间游");
        mindMap.put("nh", "离经易道");
        mindMap.put("dj", "毒经");
        mindMap.put("nd", "补天诀");
        mindMap.put("mw", "莫问");
        mindMap.put("ng", "相知");
        mindMap.put("ax", "傲血战意");
        mindMap.put("ct", "铁牢律");
        mindMap.put("hs", "易筋经");
        mindMap.put("hst", "洗髓经");
        mindMap.put("fy", "焚影圣诀");
        mindMap.put("mt", "明尊琉璃体");
        mindMap.put("cy", "分山劲");
        mindMap.put("cyt", "铁骨衣");
        mindMap.put("qc", "紫霞功");
        mindMap.put("jc", "太虚剑意");
        mindMap.put("tl", "天罗诡道");
        mindMap.put("jy", "惊羽诀");
        mindMap.put("cj", "问水诀");
        mindMap.put("gb", "笑尘诀");
        mindMap.put("bd", "北傲诀");
        mindMap.put("pl", "凌海诀");
        mindMap.put("lx", "隐龙诀");
        mindMap.put("yt", "太玄经");
        mindSet = new HashSet<>(mindMap.values());
    }

    @Autowired
    MiraiConfig miraiConfig;
    @Autowired
    JxQueryApiService jxQueryApiService;
    @Autowired
    QqGroupMapper qqGroupMapper;
    private Map<String, Long> messageTime = new ConcurrentHashMap<>();

    {
        allKey.put("日常", this::sendDaily);
        allKey.put("开服", this::getServerStatus);
        allKey.put("沙盘", this::getSand);
        allKey.put("骚话", this::getRandom);
        allKey.put("切奶", this::getSb);
        allKey.put("功能", this::getFunction);
        allKey.put("日记", this::getDog);
        allKey.put("金价", this::getMoney);
        allKey.put("骚图", this::getImageUrl);
        allKey.put("服务器", this::getServer);
        allKey.put("奇遇", this::getSerendipity);
        allKey.put("花价", this::getFlower);
        allKey.put("更新公告", this::getAnnounce);
        allKey.put("资历排行", this::getSeniority);
        allKey.put("全服资历排行", this::getAllSeniority);
        allKey.put("夸我", this::getLikeMe);
        noAllKey.put("宏 ", this::getMacro);
        noAllKey.put("小药 ", this::getHeighten);
        noAllKey.put("前置 ", this::getMethod);
        noAllKey.put("pve ", this::getEquipment);
        noAllKey.put("pvp ", this::getEquipment);
        noAllKey.put("服务器 ", this::setServer);
        noAllKey.put("奇遇 ", this::getSerendipity);
        noAllKey.put("花价 ", this::getFlower);
        noAllKey.put("成就 ", this::getAchievement);
        noAllKey.put("资历排行 ", this::getSeniority);
        noAllKey.put("全服资历 ", this::getSeniority);
        FileReader fileReader = new FileReader(new File("./jx3data/imgUrl.txt"));
        imageUrls = fileReader.readLines();
    }

    private void getLikeMe(String id) {
        String rep = HttpUtil.get("https://chp.shadiao.app/api.php");
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(rep).build());
        sendGroupMessage(id, messagesList);
    }

    private void getAllSeniority(String id) {
        getSeniority(id, "全服资历排行 ");
    }

    private void getSeniority(String id, String mp) {
        int server = 1;//默认本服
        if (mp.contains("全服")) {
            server = 0;
            mp = mp.replace("全服", "");
        }
        mp = mp.replace("资历排行 ", "");
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        JSONObject data = jxQueryApiService.getSeniority(qqGroup.getServer(), mp, server);
        List<Message> messagesList = new ArrayList<>();
        if (data != null) {
            List<JSONObject> dataList = data.getJSONArray("data").toJavaList(JSONObject.class);
            int finalServer = server;
            dataList.subList(0, 10).forEach(jsonObject -> {
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("ID:" + jsonObject.getString("name")
                        + "\n资历:" + jsonObject.getString("value")).build());
                if (finalServer == 0) {
                    messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(
                            "\n服务器:" + jsonObject.getString("server")
                                    + "\n大区:" + jsonObject.getString("region")).build());
                }
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("\n————————————————\n").build());
            });
        }
        sendGroupMessage(id, messagesList);
    }

    private void getSeniority(String id) {
        getSeniority(id, "资历排行 ");
    }

    private void getFlower(String id) {
        getFlower(id, "花价 ");
    }

    private void getFlower(String id, String text) {
        text = text.replace("花价 ", "");
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        List<Message> messagesList = new ArrayList<>();
        JSONObject data = jxQueryApiService.getFlower(qqGroup.getServer(), text);
        if (data != null) {
            //返回数据
            Map<String, Object> innerMap = data.getInnerMap();
            innerMap.forEach((s, o) -> {
                JSONArray d = (JSONArray) o;
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(s + ":\n").build());
                List<Flower> ts = d.toJavaList(Flower.class);
                for (int i = 0; i < ts.size(); i++) {
                    Flower t = ts.get(i);
                    messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(t.getName() + ":" + (t.getColor() == null ? "" : t.getColor() + ",") + "倍率:" + t.getPrice() + ",线路:" + Arrays.toString(t.getLine())).build());
                    if (i != ts.size() - 1 || ts.size() == 1) {
                        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("\n").build());
                    }
                }
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("\n————————————————\n").build());
            });
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("无数据").build());
        }
        sendGroupMessage(id, messagesList);
    }

    private void getImageUrl(String id) {
        List<Message> messagesList = new ArrayList<>();
        Random random = new Random();
        int n = random.nextInt(imageUrls.size());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_IMG).url(imageUrls.get(n)).build());
        sendGroupMessage(id, messagesList);
    }

    private void getAnnounce(String id) {
        JSONObject data = jxQueryApiService.getAnnounce();
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(data.getString("title") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(data.getString("url")).build());
        sendGroupMessage(id, messagesList);
    }


    private void getAchievement(String id, String key) {
        key = key.replace("成就 ", "");
        JSONObject rep = jxQueryApiService.getAchievement(key);
        if (rep.getInteger("code") == 200) {
            List<Message> messagesList = new ArrayList<>();
            JSONObject data = rep.getJSONObject("data");
            List<JSONObject> achievements = data.getJSONArray("achievements").toJavaList(JSONObject.class);
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("找到以下" + achievements.size() + "条数据:\n").build());
            for (int i = 0; i < achievements.size(); i++) {
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【名称】" + achievements.get(i).getString("Name") + "\n").build());
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【资历】" + achievements.get(i).getString("Point") + "\n").build());
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【描述】" + achievements.get(i).getString("Desc") + "\n").build());
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【攻略地址】" + achievements.get(i).getString("Link")).build());
                if (i != achievements.size() - 1) {
                    messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("\n\n").build());
                }
            }
            sendGroupMessage(id, messagesList);
        }
    }

    private void getSerendipity(String id) {
        getSerendipity(id, "奇遇 ");
    }

    private void getSerendipity(String id, String text) {
        text = text.replace("奇遇 ", "");
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        JSONArray daily = jxQueryApiService.getSerendipity(qqGroup.getServer(), text);
        List<Message> messagesList = new ArrayList<>();
        if (daily == null || daily.isEmpty()) {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("无数据").build());
        } else {
            List<JSONObject> jsonObjects = daily.toJavaList(JSONObject.class);
            for (int i = 0; i < jsonObjects.size(); i++) {
                Long time = Long.valueOf(jsonObjects.get(i).getString("time") + "000");
                Date date = new Date(time);
                //+ DateUtil.format(new Date(j.getString("time")), "yyyy-MM-dd")
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("ID:" + jsonObjects.get(i).getString("name")
                        + "\n名称:" + jsonObjects.get(i).getString("serendipity")
                        + "\n时间" + DateUtil.format(date, "yyyy年MM月dd日 HH:mm")
                        + (i < jsonObjects.size() - 1 ? "\n————————————————\n" : "")).build());
            }
        }
        sendGroupMessage(id, messagesList);

    }

    private void getMoney(String id) {
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        JSONObject daily = jxQueryApiService.getMoney(qqGroup.getServer());
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【服务器】:" + daily.getString("server") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【5173】:" + daily.getString("5173") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【7881】:" + daily.getString("7881") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【万宝楼】:" + daily.getString("wanbaolou") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【uu898】:" + daily.getString("uu898") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【dd373】:" + daily.getString("dd373")).build());
        sendGroupMessage(id, messagesList);
    }

    private void setServer(String id, String server) {
        server = server.replace("服务器 ", "");
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        JSONObject data = jxQueryApiService.getServer(server);
        List<Message> messagesList = new ArrayList<>();
        String mainServer = "梦江南";
        if (data == null) {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("服务器错误!不支持简称!").build());
        } else {
            mainServer = data.getString("server");
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("服务器设置成功!服务器:" + mainServer).build());
        }
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setGroupId(id);
            qqGroup.setServer(mainServer);
            qqGroupMapper.insert(qqGroup);
        } else {
            qqGroup.setServer(mainServer);
            qqGroupMapper.updateById(qqGroup);
        }
        sendGroupMessage(id, messagesList);
    }


    @Bean(name = "qqWebSocketClient")
    public WebSocketClient qqWebSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://" + miraiConfig.getUrl() + "/message?sessionKey=" + miraiConfig.getSession()), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[QQ-Message] 连接成功");
                    groupSet.addAll(qqGroupMapper.selectList(new QueryWrapper<>()));
                }

                @Override
                public void onMessage(String message) {
                    log.info("[QQ-Message] 收到消息={}", message);
                    Advices msg = JSONObject.parseObject(message, Advices.class);
                    //私聊消息处理 弃用开启功能
                    if (msg.getSender().getGroup() == null) {
                        List<Message> messageChain = msg.getMessageChain();
                        List<Message> messagesList = new ArrayList<>();
                        messageChain.forEach(messageVo -> {
                            /**
                             if (messageVo.getType().equals(MiraiConst.MESSAGE_TYPE_TEXT) && messageVo.getText().contains("开启")) {
                             String groupId = messageVo.getText().replace("开启", "");
                             QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, groupId));
                             if (qqGroup == null) {
                             qqGroupMapper.insert(QqGroup.builder().groupId(groupId).status(1).build());
                             } else {
                             qqGroup.setStatus(1);
                             qqGroupMapper.updateById(qqGroup);
                             }
                             groupSet.add(groupId);
                             //发送私聊消息
                             List<Message> messagesChain = new ArrayList<>();
                             messagesChain.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("开启成功!").build());
                             sendFriendMessage(msg.getSender().getId(), messagesChain);
                             } else if (messageVo.getType().equals(MiraiConst.MESSAGE_TYPE_TEXT) && messageVo.getText().contains("关闭")) {
                             String groupId = messageVo.getText().replace("关闭", "");
                             QqGroup qqGroup1 = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getStatus, 1).eq(QqGroup::getGroupId, groupId));
                             if (qqGroup1 != null) {
                             qqGroup1.setStatus(0);
                             qqGroupMapper.updateById(qqGroup1);
                             groupSet.remove(groupId);
                             //关闭成功
                             List<Message> messagesChain = new ArrayList<>();
                             messagesChain.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("关闭成功!").build());
                             sendFriendMessage(msg.getSender().getId(), messagesChain);
                             } else {
                             //未开启或不存在
                             List<Message> messagesChain = new ArrayList<>();
                             messagesChain.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("未开启或不存在!").build());
                             sendFriendMessage(msg.getSender().getId(), messagesChain);
                             }
                             }
                             */
                        });
//                        sendFriendMessage(msg.getSender().getId(), messagesList);
                    }
                    //群消息处理
                    if (msg.getSender().getGroup() != null) {
                        List<Message> messageChain = msg.getMessageChain();
                        messageChain.forEach(messageVo -> {
                            if (messageVo.getType().equals(MiraiConst.MESSAGE_TYPE_SOURCE)) {
                                if (messageTime.containsKey(msg.getSender().getGroup().getId())) {
                                    DateTime date = DateUtil.date(messageTime.get(msg.getSender().getGroup().getId()));
                                    long between = DateUtil.between(date, new Date(), DateUnit.MINUTE);
                                    if (between > 10) {
                                        //发言间隔差距10分钟 随机骚话或骚图
                                        if (RandomUtil.randomInt() % 2 == 0) {
                                            //骚话
                                            getRandom(msg.getSender().getGroup().getId());
                                        } else {
                                            //骚图
                                            getImageUrl(msg.getSender().getGroup().getId());
                                        }
                                    }
//                                    } else {
//                                        //不超过10分钟 则10%概率触发
//                                        WeightRandom<Integer> weightRandom = new WeightRandom<>();
//                                        weightRandom.add(1, 0.1);
//                                        weightRandom.add(2, 0.9);
//                                        if (weightRandom.next() == 1) {
//                                            if (RandomUtil.randomInt() % 2 == 0) {
//                                                //骚话
//                                                getRandom(msg.getSender().getGroup().getId());
//                                            } else {
//                                                //骚图
//                                                getImageUrl(msg.getSender().getGroup().getId());
//                                            }
//                                        }
//
//                                    }
                                }
                                //更新最后发言时间
                                messageTime.put(msg.getSender().getGroup().getId(), messageVo.getTime() * 1000);
                            }
                            //目前只处理文字消息 并且只有jx3Api功能
                            if (messageVo.getType().equals(MiraiConst.MESSAGE_TYPE_TEXT)) {
                                String key = messageVo.getText();
                                //完全匹配
                                AllMatchKeyMethod allMatchKeyMethod = allKey.get(key);
                                if (allMatchKeyMethod != null) {
                                    allMatchKeyMethod.exec(msg.getSender().getGroup().getId());
                                } else {
                                    Set<Map.Entry<String, NoAllMatchKeyMethod>> entries = noAllKey.entrySet();
                                    entries.forEach(stringNoAllMatchKeyMethodEntry -> {
                                        if (key.contains(stringNoAllMatchKeyMethodEntry.getKey())) {
                                            stringNoAllMatchKeyMethodEntry.getValue().exec(msg.getSender().getGroup().getId(), key);
                                        }
                                    });
                                }
                            }
                        });
                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[QQ-Message] 退出连接");
                }

                @Override
                public void onError(Exception ex) {
                    log.info("[QQ-Message] 连接错误={}", ex.getMessage());
                }
            };
            new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(1000 * 60);
                        webSocketClient.send("");
                    } catch (Exception e) {
                        if (webSocketClient.getReadyState().name().equals(ReadyState.CLOSED.name()) || webSocketClient.getReadyState().name().equals(ReadyState.CLOSING.name())) {
                            log.info("[QQ-Message]重连......");
                            webSocketClient.reconnect();
                        }
                    }
                }
            }).start();
            webSocketClient.connect();
            return webSocketClient;
        } catch (URISyntaxException uriSyntaxException) {
            uriSyntaxException.printStackTrace();
        }
        return null;
    }

    @Bean(name = "jx3WebSocketClient")
    public WebSocketClient jx3WebSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("wss://socket.nicemoe.cn"), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[jx3Api] 连接成功");
                }

                @Override
                public void onMessage(String message) {
                    log.info("[jx3Api] 收到消息={}", message);
                    JxAdvices msg = JSONObject.parseObject(message, JxAdvices.class);
                    if (msg.getType() == 2001) {
                        log.info("[开服数据]:{}", msg);
                        //开服播报
                        List<Message> messagesList = new ArrayList<>();
                        if (msg.getData().getInteger("status") == 1) {
                            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("开服了！！！冲！！！").build());
                        } else {
                            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("维护了！！！").build());
                        }
                        groupSet.forEach(group -> {
                            if (msg.getData().getString("server").equals(group.getServer())) {
                                sendGroupMessage(group.getGroupId(), messagesList);
                            }
                        });

                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[jx3Api] 退出连接");
                }

                @Override
                public void onError(Exception ex) {
                    log.info("[jx3Api] 连接错误={}", ex.getMessage());
                }
            };
            webSocketClient.connect();
            new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(1000 * 60);
                        webSocketClient.send("");
                    } catch (Exception e) {
                        if (webSocketClient.getReadyState().name().equals(ReadyState.CLOSED.name()) || webSocketClient.getReadyState().name().equals(ReadyState.CLOSING.name())) {
                            log.info("[jx3Api]重连......");
                            webSocketClient.reconnect();
                        }
                    }
                }
            }).start();
            //如果断线，则重连并重新发送验证信息
            return webSocketClient;
        } catch (URISyntaxException uriSyntaxException) {
            uriSyntaxException.printStackTrace();
        }
        return null;

    }

    @Bean(name = "eventSocketClient")
    public WebSocketClient eventSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://" + miraiConfig.getUrl() + "/event?sessionKey=" + miraiConfig.getSession()), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[QQ-Event] 连接成功");
                }

                @Override
                public void onMessage(String message) {
                    log.info("[QQ-Event] 收到消息={}", message);
                    EventRequest eventRequest = JSONObject.parseObject(message, EventRequest.class);
                    if (eventRequest.getType().equals(MiraiConst.EVENT_TYPE_NEW_FRIEND) && eventRequest.getMessage().equals("JX3BOX")) {
                        //处理好友请求 好友申请关键字必须为JX3BOX 才通过
                        sendFriendResponse(eventRequest);
                    } else if (eventRequest.getType().equals(MiraiConst.EVENT_TYPE_NEW_GROUP)) {
                        //处理入群消息
                        sendGroupResponse(eventRequest);
                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[QQ-Event] 退出连接");
                }

                @Override
                public void onError(Exception ex) {
                    log.info("[QQ-Event] 连接错误={}", ex.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (URISyntaxException uriSyntaxException) {
            uriSyntaxException.printStackTrace();
        }
        return null;

    }

    private void getHeighten(String target, String text) {
        String xf = text.replace("小药 ", "");
        String s = mindMap.get(xf);
        if (s == null && xf.length() > 1) {
            for (String mind : mindSet) {
                if (mind.contains(xf)) {
                    s = mind;
                    break;
                }
            }
        }
        List<Message> messagesList = new ArrayList<>();
        if (s != null) {
            JSONObject data = jxQueryApiService.getHeighten(s);
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【增强食品】:" + data.getString("heightenFood") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【辅助食品】:" + data.getString("auxiliaryFood") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【增强药品】:" + data.getString("heightenDrug") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【辅助药品】:" + data.getString("auxiliaryDrug")).build());
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("心法错误!").build());
        }
        sendGroupMessage(target, messagesList);
    }

    private void getMethod(String id, String text) {
        String key = text.replace("前置 ", "");
        JSONObject data = jxQueryApiService.getMethod(key);
        List<Message> messagesList = new ArrayList<>();
        if (data != null) {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【名称】:" + data.getString("name") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【方式】:" + data.getString("method") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【条件】:" + data.getString("need") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【其他】:" + data.getString("other") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【物品奖励】:" + data.getString("reward")).build());
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("暂无数据!").build());
        }
        sendGroupMessage(id, messagesList);
    }

    private void getEquipment(String id, String text) {
        boolean flag = !text.contains("pvp");
        String xf = text.replace("pve ", "");
        String xf2 = xf.replace("pvp ", "");
        List<Message> messagesList = new ArrayList<>();
        String s = mindMap.get(xf2);
        if (s == null && xf.length() > 1) {
            for (String mind : mindSet) {
                if (mind.contains(xf2)) {
                    s = mind;
                    break;
                }
            }
        }
        if (s != null) {
            JSONObject result = jxQueryApiService.getEquipment(s);
            if (flag) {
                //pve
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_IMG).url(result.getString("pveUrl")).build());
            } else {
                //pvp
                messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_IMG).url(result.getString("pvpUrl")).build());
            }
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("心法错误!").build());
        }
        sendGroupMessage(id, messagesList);
    }

    private void getMacro(String target, String text) {
        String xf = text.replace("宏 ", "");
        String s = mindMap.get(xf);
        List<Message> messagesList = new ArrayList<>();
        if (s == null && xf.length() > 1) {
            for (String mind : mindSet) {
                if (mind.contains(xf)) {
                    s = mind;
                    break;
                }
            }
        }
        if (s != null) {
            if (s.equals("问水诀")) {
                s = "山居剑意";
            }
            JSONObject h = jxQueryApiService.getMacro(s);
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(h.getString("name") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(h.getString("plan") + "\n").build());
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(h.getString("command")).build());
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("心法错误!").build());
        }
        sendGroupMessage(target, messagesList);
    }

    private void getServer(String id) {
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        List<Message> messagesList = new ArrayList<>();
        if (qqGroup == null) {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("默认服务器:梦江南").build());
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("服务器:" + qqGroup.getServer()).build());
        }
        sendGroupMessage(id, messagesList);
    }

    private void getRandom(String id) {
        JSONObject data = jxQueryApiService.getRandom();
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(data.getString("text")).build());
        sendGroupMessage(id, messagesList);
    }

    private void getFunction(String id) {
        List<Message> messageChainList = new ArrayList<>();
        messageChainList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("日常 | 开服 | 更新公告 | 沙盘 ｜ 金价 | 骚话(图) | 日记(夸我) | 服务器" + "\n").build());
        messageChainList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("成就 另一边的故事 | 宏 jy(惊羽) | 小药 jy(惊羽) | 前置 三山四海｜pve jy(惊羽) | pvp jy(惊羽) " + "\n").build());
        messageChainList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("奇遇 [ID(可选)] [奇遇名称(可选)] | 花价 [鲜花(可选)] [线路(可选)]" + "\n").build());
        messageChainList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("资历排行 [门派(可选)] ｜ 全服资历 [门派(可选)]" + "\n").build());
        messageChainList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("注:本机器人由双梦木桩团贡献～").build());
        sendGroupMessage(id, messageChainList);
    }

    private void getSb(String id) {
        List<GroupMember> memberList = getMemberList(Integer.valueOf(id));
        if (memberList.stream().anyMatch(member -> member.getId().equals("540226099") || member.getId().equals("958590707") || member.getId().equals("773683674"))) {
            List<Message> messageChainList = new ArrayList<>();
            Message toMessage = new Message();
            toMessage.setType("Plain");
            long count = memberList.stream().filter(groupMember -> groupMember.getId().equals("958590707")).count();
            long count2 = memberList.stream().filter(groupMember -> groupMember.getId().equals("773683674")).count();
            if (count > 0 && count2 <= 0) {
                toMessage.setText("玩奶不得抽死你这个王八蛋");
            } else if (count <= 0 && count2 > 0) {
                toMessage.setText("你让毒经公主切奶？");
            } else {
                if (RandomUtil.randomInt() % 2 == 0) {
                    toMessage.setText("玩奶不得抽死你这个王八蛋");
                } else {
                    toMessage.setText("你让毒经公主切奶？");
                }
            }
            messageChainList.add(toMessage);
            sendGroupMessage(id, messageChainList);
        }
    }

    private void getDog(String id) {
        JSONObject data = jxQueryApiService.getDog();
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text(data.getString("text")).build());
        sendGroupMessage(id, messagesList);
    }

    private void getSand(String id) {
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        JSONObject sand = jxQueryApiService.getSand(qqGroup.getServer());
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_IMG).url(sand.getString("url")).build());
        sendGroupMessage(id, messagesList);
    }

    private void getServerStatus(String id) {
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, id));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        JSONObject serverStatus = jxQueryApiService.getServerStatus(qqGroup.getServer());
        List<Message> messagesList = new ArrayList<>();
        if (serverStatus.getInteger("status") == 1) {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("开服了!这不冲?").build());
        } else {
            messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("维护中......").build());
        }
        sendGroupMessage(id, messagesList);
    }

    private void sendDaily(String target) {
        QqGroup qqGroup = qqGroupMapper.selectOne(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, target));
        if (qqGroup == null) {
            qqGroup = new QqGroup();
            qqGroup.setServer("梦江南");
        }
        JSONObject daily = jxQueryApiService.getDaily(qqGroup.getServer());
        List<Message> messagesList = new ArrayList<>();
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【大战】:" + daily.getString("DayWar") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【战场】:" + daily.getString("DayBattle") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【矿车】:" + daily.getString("DayCamp") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【公共日常】:" + daily.getString("DayCommon") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【公共周常】:" + daily.getString("WeekCommon") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【周常十人本】:" + daily.getString("WeekTeam") + "\n").build());
        messagesList.add(Message.builder().type(MiraiConst.MESSAGE_TYPE_TEXT).text("【周常五人本】:" + daily.getString("WeekFive")).build());
        sendGroupMessage(target, messagesList);
    }

    private void sendGroupResponse(EventRequest eventRequest) {
        EventResponse eventResponse = new EventResponse();
        eventResponse.setSessionKey(miraiConfig.getSession());
        eventResponse.setEventId(eventRequest.getEventId());
        eventResponse.setFromId(eventRequest.getFromId());
        eventResponse.setGroupId(eventRequest.getGroupId());
        eventResponse.setMessage("");
        eventResponse.setOperate(0);
        HttpResponse resVerify = HttpUtil.createPost(miraiConfig.getUrl() + "/resp/botInvitedJoinGroupRequestEvent").body(JSONObject.toJSONString(eventResponse)).execute();
        JSONObject resVerifyJson = JSONObject.parseObject(resVerify.body());
        log.info("sendGroupResponse:{}", resVerifyJson.toJSONString());
        //存入数据库
        if (qqGroupMapper.selectList(new LambdaQueryWrapper<QqGroup>().eq(QqGroup::getGroupId, eventRequest.getGroupId().toString())).isEmpty()) {
            QqGroup qqGroup = new QqGroup();
            qqGroup.setGroupId(eventRequest.getGroupId().toString());
            qqGroupMapper.insert(qqGroup);
            groupSet.add(qqGroup);
        }
    }

    private void sendFriendResponse(EventRequest eventRequest) {
        EventResponse eventResponse = new EventResponse();
        eventResponse.setSessionKey(miraiConfig.getSession());
        eventResponse.setEventId(eventRequest.getEventId());
        eventResponse.setFromId(eventRequest.getFromId());
        eventResponse.setGroupId(eventRequest.getGroupId());
        eventResponse.setMessage("");
        eventResponse.setOperate(0);
        log.info(JSONObject.toJSONString(eventResponse));
        HttpResponse resVerify = HttpUtil.createPost(miraiConfig.getUrl() + "/resp/newFriendRequestEvent").body(JSONObject.toJSONString(eventResponse)).execute();
        JSONObject resVerifyJson = JSONObject.parseObject(resVerify.body());
        log.info("sendFriendResponse:{}", resVerifyJson.toJSONString());
    }

    private void sendGroupMessage(String target, List<Message> messageChainList) {
        Map<String, Object> params = new HashMap<>();
        params.put("sessionKey", miraiConfig.getSession());
        params.put("target", target);
        params.put("messageChain", messageChainList);
        HttpResponse resVerify = HttpUtil.createPost(miraiConfig.getUrl() + "/sendGroupMessage").body(JSONObject.toJSONString(params)).execute();
        JSONObject resVerifyJson = JSONObject.parseObject(resVerify.body());
        log.info("sendGroupMessageRep:{}", resVerifyJson.toJSONString());
    }

    private void sendFriendMessage(String target, List<Message> messageChainList) {
        Map<String, Object> params = new HashMap<>();
        params.put("sessionKey", miraiConfig.getSession());
        params.put("target", target);
        params.put("messageChain", messageChainList);
        HttpResponse resVerify = HttpUtil.createPost(miraiConfig.getUrl() + "/sendFriendMessage").body(JSONObject.toJSONString(params)).execute();
        JSONObject resVerifyJson = JSONObject.parseObject(resVerify.body());
        log.info("sendFriendMessage:{}", resVerifyJson.toJSONString());
    }

    private List<GroupMember> getMemberList(Integer target) {
        String res = HttpUtil.get(miraiConfig.getUrl() + "/memberList?sessionKey=" + miraiConfig.getSession() + "&target=" + target);
        return JSONObject.parseArray(res, GroupMember.class);
    }

}
